package com.yz.springtest.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class ReflectTest {
	public static Car initByDefaultConst() throws Throwable {
		
		//通过类装载器获取Car类对象
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		Class clazz = loader.loadClass("com.yz.springtest.reflect.Car");
		
		//获取类默认构造器 并通过它实例化Car
		Constructor cons = clazz.getDeclaredConstructor((Class[])null);
		Car car = (Car)cons.newInstance();
		
		//通过反射方法 设置属性。
		Method setBrand = clazz.getMethod("setBrand", String.class);
		setBrand.invoke(car, "奥迪");
		
		Method setColor = clazz.getMethod("setColor", String.class);
		setColor.invoke(car, "黑");
		
		Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
		setMaxSpeed.invoke(car, 200);
		
		return car;
	}
	
	public static void main(String[] args) throws Throwable {
		Car car = new ReflectTest().initByDefaultConst();
		car.introduce();
	}
}
